package com.mediacloud.app.newsmodule.activity;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.chinamcloud.audioserver.APSHelper;
import com.chinamcloud.audioserver.MusicEntity;
import com.chinamcloud.audioserver.TaskAudioConfig;
import com.chinamcloud.collect.AcquisitionManager;
import com.chinamcloud.report.ReportKit;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.assembly.util.StringUtils;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.adaptor.BaseAdaptor;
import com.mediacloud.app.model.eventbus.event.LoginEvent;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter;
import com.mediacloud.app.newsmodule.utils.AddMedalStatistics;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.KillMusicUtils;
import com.mediacloud.app.newsmodule.utils.NewsDetailInvoker;
import com.mediacloud.app.newsmodule.utils.ToastUtil;
import com.mediacloud.app.newsmodule.view.AudioBottomPopWin;
import com.mediacloud.app.newsmodule.view.BaseSpiderView;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.user.model.UserInfo;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 音频直播类
 *
 * @author x
 */
@SuppressWarnings("ALL")
public class AudioVodDetailActivityHalf extends BaseAudioActivityHalf {
    //码率
    private AudioBottomPopWin<String> audioBottomPopWin;
    private List<String> bitRateUrls = new ArrayList<>();
    private List<String> bitRateTitles = new ArrayList<String>();
    private AudioStreamLineAdaptor bitRateAdapter;

    private List<String> speedList = new ArrayList<>();
    private AudioSpeedAdaptor speedAdaptor;

    private boolean isLoop = false;
    private int speedIndex = 1;
    private int bitRateIndex = 0;
    private NewsDetailInvoker newsDetailInvoker;
    private AudioDetailCallBack audioDetailCallBack;

    protected List<ArticleItem> audioList = new ArrayList<ArticleItem>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        audioBottomPopWin = new AudioBottomPopWin<>(this);
        loopModeBtn.setOnClickListener(this);
        speedIv.setOnClickListener(this);
        setAudioPlayInfo();
        audioDetailCallBack = new AudioDetailCallBack();
        newsDetailInvoker = new NewsDetailInvoker(audioDetailCallBack);
        getAudioDetail();
        updatePlayModeDrawable();
        onPageStart();
    }

    private void setAudioPlayInfo() {
        speedList.add("0.5X");
        speedList.add("正常速度");
        speedList.add("1.5X");
        speedList.add("2.0X");
        TaskAudioConfig config = APSHelper.getTaskConfig("" + articleItem.getId());
        if (config != null) {
            try {

                isLoop = config.getLoop();
                speedIndex = config.getSpeedIndex();
                bitRateIndex = config.getBitRateIndex();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        speedIv.setVisibility(View.VISIBLE);
        setSpeed();
    }


    private void setSpeed() {
        switch (speedIndex) {
            case 0:
                speedIv.setImageResource(R.drawable.audio_speed0);
                changeSpeed(0.5f);
                break;
            case 1:
                speedIv.setImageResource(R.drawable.audio_speed1);
                changeSpeed(1.0f);
                break;
            case 2:
                speedIv.setImageResource(R.drawable.audio_speed2);
                changeSpeed(1.5f);
                break;
            case 3:
                speedIv.setImageResource(R.drawable.audio_speed3);
                changeSpeed(2.0f);
                break;
        }
    }


    @Override
    protected void onPaidAudio(String audio) {
        articleItem.setAudio(audio);
        optPlayUrl();
    }


    public void fault(Object data) {

    }

    @Override
    public void onToggleClick() {
        super.onToggleClick();
        apsKit.setLoop(isLoop);
        setSpeed();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.loopModeBtn) {
            isLoop = !isLoop;
            updatePlayModeDrawable();
            apsKit.setLoop(isLoop);
        } else if (v.getId() == R.id.speedIv) {
            showSpeedView();
        }

    }

    /**
     * 选择倍速弹框
     */

    private void showSpeedView() {
        if (audioBottomPopWin.isShowing()) {
            return;
        }
        if (speedAdaptor == null) {
            speedAdaptor = new AudioSpeedAdaptor(this, speedList);
        }
        audioBottomPopWin.setListAdaptor(speedAdaptor);
        audioBottomPopWin.setPopTitle("选择倍速");
        audioBottomPopWin.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                speedIndex = position;
                setSpeed();
            }
        });
        audioBottomPopWin.showAtLocation(mRootView, Gravity.BOTTOM, 0, 0);
        backgroundAlpha(0.8f);
        audioBottomPopWin.setOnDismissListener(() -> {
            backgroundAlpha(1f);
        });
    }

    private void changeSpeed(float speed) {
        apsKit.setSpeed(speed);
    }


    protected void updatePlayModeDrawable() {
        Drawable drawable = null;
        if (isLoop) {
            drawable = ContextCompat.getDrawable(this, R.drawable.audio_loop_open);
        } else {
            drawable = ContextCompat.getDrawable(this, R.drawable.audio_loop_close);
        }
        loopModeBtn.normalImg = loopModeBtn.pressImg = drawable;
        loopModeBtn.updateEffDrawable();
    }


    class AudioDetailCallBack implements DataInvokeCallBack<ArticleItemReciver> {
        @Override
        public void success(ArticleItemReciver data) {
            if (data.state) {
                if (articleItem != null && articleItem.getFromComponent() != 1)
                    articleItem = data.articleItem;
                     ReportKit.INSTANCE.escalationArticle(articleItem.getId()+"", articleItem.getTitle(),articleItem.getPublishdate(),articleItem.getAddUser());

                if (articleItem.getSpider() != null) {
                    BaseSpiderView spiderView = findViewById(R.id.spiderView);
                    spiderView.setDate(articleItem);
                }
                if (TextUtils.isEmpty(articleItem.getSummary())) {
                    setCl_lyaoutVisiable(View.GONE);
                } else {
                    setCl_lyaoutVisiable(View.VISIBLE);
                    audioDes.setText(articleItem.getSummary());
                }
                tvPlayCount.setText(StringUtils.toTenThousand(articleItem.getHitCount_format()) + "播放");
                if (TextUtils.isEmpty(articleItem.getAuthor())) {
                    tvAuthor.setVisibility(View.GONE);
                } else {
                    tvAuthor.setVisibility(View.VISIBLE);
                    tvAuthor.setText(articleItem.getAuthor());
                }
                tvPublishData.setText(articleItem.getPublishdate_format());
                //推送过来没有logo
                FunKt.load(logoView, articleItem.getLogo()
                        , 10, AppFactoryGlobalConfig.getDefaultImageLoadDrawable(), null);
                loadedImg = false;
                refreshBottomStyle(data.articleItem, 1);
                //seekbar.setEnabled(true);
                if (TextUtils.isEmpty(articleItem.getGoodsID())) {
                    normalPayUtil.showPaidView();
                    optPlayUrl();
                } else {
                    normalPayUtil.judgeShowPayView(articleItem);
                }
                startAddIntegralCounter();
                AddMedalStatistics.addMedalStatistics(AudioVodDetailActivityHalf.this); //勋章统计
                //getComponentData();
            } else {
                ToastUtil.show(AudioVodDetailActivityHalf.this, R.string.noraml_newserror);

            }
            broccoliLayout.setVisibility(View.GONE);
            mErrorView.setVisibility(View.GONE);
        }

        @Override
        public void fault(Object data) {
            ToastUtil.show(AudioVodDetailActivityHalf.this, R.string.noraml_newserror);
        }
    }

    public void startAddIntegralCounter(){
        AddIntegralCounter.start(this, new AddIntegralCounter.TimeoutCallback() {
            @Override
            public void timeoutCallback() {
                if (articleItem == null){
                    return;
                }
                Addintegral.addintegral(AudioVodDetailActivityHalf.this, articleItem.getId(), 2, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0",articleItem);
            }
        });
    }

    protected void optPlayUrl() {

        try {
            JSONObject video = new JSONObject(articleItem.getAudio());
            JSONArray tsAddress = video.optJSONArray("PC");
            cdnEncrypt = video.optString("cdnConfigEncrypt");
            bitRateTitles.clear();
            bitRateUrls.clear();
            for (int i = 0; i < tsAddress.length(); i++) {
                JSONObject line = tsAddress.optJSONObject(i);
                String title = line.optString("title");
                String url = line.optString("url");
                bitRateUrls.add(url);
                bitRateTitles.add(title);
            }

            if (bitRateIndex < bitRateUrls.size()) {
                musicEntity = new MusicEntity(articleItem.getTitle(),bitRateUrls.get(bitRateIndex));
                musicEntity.setAlbum("");
                musicEntity.setSinger("");
                if (isAPSPrepared) {
                    apsKit.setData(musicEntity);
                }
                String title = bitRateTitles.get(bitRateIndex);
                streamLineBtn.setText(title);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.show(this, R.string.noraml_newserror);
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }


    @Override
    protected List<View> getPaidViews() {
        List<View> list = new ArrayList<>();
        list.add(seekbar);
        return list;
    }

    @Override
    public void finish() {
        super.finish();
        if(apsKit.isPlaying()){
            if(apsKit.isTaskPlaying()){
                TaskAudioConfig config = new TaskAudioConfig(isLoop, speedIndex, bitRateIndex);
                APSHelper.saveTaskConfig("" + articleItem.getId(),config);
            }
            sendShowFloaWinMsg();
        }else{
            KillMusicUtils.hideReadNewsWin();
            realFinish();
        }
    }

    protected void getAudioDetail() {
        if (isFinish)
            return;
        String navigate_id = catalogItem != null ? catalogItem.getCatid() : "";
        newsDetailInvoker.getArticleById(String.valueOf("" + articleItem.getId()), navigate_id);
    }


    @Override
    protected void showStreamLine() {
        if (audioBottomPopWin.isShowing()) {
            return;
        }
        if (bitRateAdapter == null) {
            bitRateAdapter = new AudioStreamLineAdaptor(this, bitRateTitles);
        }
        audioBottomPopWin.setListAdaptor(bitRateAdapter);
        audioBottomPopWin.setPopTitle("选择在线播放音质");
        audioBottomPopWin.showAtLocation(mRootView, Gravity.BOTTOM, 0, 0);
        audioBottomPopWin.setItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                bitRateIndex=position;
                String title = bitRateTitles.get(position);
                streamLineBtn.setText(title);
                MusicEntity entity = new MusicEntity(articleItem.getTitle(),bitRateUrls.get(position));
                entity.setAlbum("");
                entity.setSinger("");
                apsKit.setData(entity);
                apsKit.resetSourceAndPlayer();
                setSpeed();
                apsKit.toggle();
            }
        });
        backgroundAlpha(0.8f);
        audioBottomPopWin.setOnDismissListener(() -> {
            backgroundAlpha(1f);
        });

    }

    /**
     * 设置添加屏幕的背景透明度(值越大,透明度越高)
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
    }


    class AudioStreamLineAdaptor extends BaseAdaptor<String> {

        public AudioStreamLineAdaptor(Context context, List<String> list) {
            super(context, list);
        }

        public AudioStreamLineAdaptor(Context context) {
            super(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.aappfactory_vod_audiosource_change_item, null);
            }
            TextView audioLineItem = Utility.findViewById(convertView, R.id.audioLineItem);
            audioLineItem.setText(getItem(position));
            ImageView imageViewCheck = Utility.findViewById(convertView, R.id.image_checked);
            if (position == bitRateIndex) {
                imageViewCheck.setImageResource(R.drawable.mous_checked);
                imageViewCheck.setVisibility(View.VISIBLE);
            } else {
                imageViewCheck.setVisibility(View.INVISIBLE);
            }
            return convertView;
        }

    }

    class AudioSpeedAdaptor extends BaseAdaptor<String> {

        public AudioSpeedAdaptor(Context context, List<String> list) {
            super(context, list);
        }

        public AudioSpeedAdaptor(Context context) {
            super(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.aappfactory_vod_audiosource_change_item, null);
            }
            TextView audioLineItem = Utility.findViewById(convertView, R.id.audioLineItem);
            audioLineItem.setText(getItem(position));
            ImageView imageViewCheck = Utility.findViewById(convertView, R.id.image_checked);

            if (position == speedIndex) {
                imageViewCheck.setImageResource(R.drawable.mous_checked);
            } else {
                imageViewCheck.setImageResource(R.drawable.mous_uncheck);
            }

            return convertView;
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        UserInfo info = UserInfo.getUserInfo(this);
        if (articleItem != null) {
            AcquisitionManager.getInstance().readEnter(info,
                    "" + articleItem.getId(), DomainUtil.getDomain(articleItem.getUrl()),
                    articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        UserInfo info = UserInfo.getUserInfo(this);
        if (articleItem != null) {
            AcquisitionManager.getInstance().readExit(info,
                    "" + articleItem.getId(), DomainUtil.getDomain(articleItem.getUrl()),
                    articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent loginEvent) {
        //20200117修复登录后页面不刷新导致无法更新付费状态的bug
        if (UserInfo.getUserInfo(this).isLogin()) {
            getAudioDetail();
        }
    }

    @Override
    public void noNetwork() {
        mErrorView.setVisibility(View.VISIBLE);
        emptyTipsText.setText("网络请求失败，请点击重试");
        mErrorView.setOnClickListener(v -> {
            if (hasNetWork)
                getAudioDetail();
            else showNetWorDialog();
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}